package com.lsmo.android.carfans.view.car;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.lsmo.android.carfans.R;
import com.lsmo.android.carfans.activity.car.BrandAdapter;
import com.lsmo.android.carfans.activity.car.BrandListActivity;
import com.lsmo.android.carfans.model.car.Brand;
import com.lsmo.android.carfans.process.car.CarProcess;
import com.lsmo.android.common.base.BaseProcess;
import com.lsmo.android.common.base.BaseTask;
import com.lsmo.android.common.base.ViewProcessCallBack;
import com.lsmo.android.util.Caller;

/**
 * @author SYX
 * @类描述：  车型中品牌Tab                  
 * @项目名称：carfans     
 * @类名称：SelectCarView                    
 * @修改时间：  
 * @修改备注： 
 */
public class SelectCarView extends LinearLayout implements ViewProcessCallBack  {
	public static final String TAG = SelectCarView.class.getSimpleName();
	
	private CarProcess carProcess;
	private ListView listView;
	ArrayList<Brand> BrandList;
	public String[] mStrings;
	public String strReString;
	private LinearLayout linearLayout1,linearLayout2;
	public Context mContext ;
	private ViewGroup mProgressBarLayout;
	public View currView;//当前view
	
	public RemoveWindow mRemoveWindow = new RemoveWindow();
	Handler mHandler = new Handler();
	public WindowManager mWindowManager;
	public TextView mDialogText;
	public boolean mShowing;
	public boolean mReady;
	public char mPrevLetter = Character.MIN_VALUE;
	
	public SelectCarView(Context context) {
		super(context);
		this.mContext = context;
		this.carProcess = new CarProcess();
		try {
			strReString = Caller.convertStreamToString(getResources().getAssets().open("brand"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		currView = ((Activity)context).getLayoutInflater().inflate(R.layout.car_main_selectcar_layout, this);
		this.postInvalidate();
		listView = (ListView)currView.findViewById(R.id.listView);//listview
		mProgressBarLayout = (ViewGroup)currView.findViewById(R.id.loading_layout);
		//暂时隐藏不用的布局
		linearLayout1 = (LinearLayout)currView.findViewById(R.id.button_relative);
		linearLayout2  = (LinearLayout)currView.findViewById(R.id.navigation_line_id);
		linearLayout1.setVisibility(View.GONE);
		linearLayout2.setVisibility(View.GONE);
		
		updateView();//加载页面数据
	}
	
	@Override
	public void processAfterTaskFinish(int code, Object result ) {
		//选择品牌
		if(code == SelectCarTask.GET_BRAND_LIST){
			if(result!=null){
				setBrandView();//加载品牌
			}
		}
		this.mProgressBarLayout.setVisibility(View.GONE);
		this.listView.setVisibility(View.VISIBLE);
	}
	
	@Override
	public void updateView() {
		// TODO Auto-generated method stub
		this.mProgressBarLayout.setVisibility(View.VISIBLE);
		this.listView.setVisibility(View.GONE);
		
//			scrollView();//加载滚动字母UI
		   
			new SelectCarTask(SelectCarTask.GET_BRAND_LIST,
					this.mContext,
					this,
					this.carProcess 
		 ).execute(new String[]{});
	}

	
	private class SelectCarTask extends BaseTask{
		public static final int GET_BRAND_LIST =2;//品牌
		private CarProcess carProcess ;
		
		public SelectCarTask(int code , Context context,ViewProcessCallBack view,BaseProcess process ) {
			super(code,context,view );
			this.carProcess = (CarProcess) process;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		@Override
		protected Object doInBackground(String... params) {
			super.doInBackground(params);
			Object result = null;
	 
			switch(this.mCode){
			    //选择品牌
				case GET_BRAND_LIST:
					
					//加载数据
					BrandList = carProcess.downloadData(strReString,null);
					
					break;
			}
			return BrandList;
		}
		
		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			switch(this.mCode){
				//选择品牌
				case GET_BRAND_LIST:
					
				 		mView.processAfterTaskFinish(this.mCode ,result );
				 	
				 	break;
		   }
		}
	}

	/**
	 * listview滚动view车型大标题
	 */
	public void scrollView(){
		mStrings = carProcess.getStrings(strReString,null);//将json转换成String[]
		mWindowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
		
		LayoutInflater inflate = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mDialogText = (TextView) inflate.inflate(R.layout.car_list_position, null);
        mDialogText.setVisibility(View.INVISIBLE);
        
        mHandler.post(new Runnable() {
            public void run() {
                mReady = true;
                WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                        WindowManager.LayoutParams.TYPE_APPLICATION,
                        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                        PixelFormat.TRANSLUCENT);
                mWindowManager.addView(mDialogText, lp);
            }});

	}
	
	/**
	 * 滑动窗体类
	 * @author SYX
	 */
	public final class RemoveWindow implements Runnable {
        public void run() {
            removeWindow();
        }
    }
	/**
	 * 滑动窗体方法
	 */
    public void removeWindow() {
        if (mShowing) {
            mShowing = false;
            mDialogText.setVisibility(View.INVISIBLE);
        }
    }
    
	//品牌
	public void setBrandView()
	{
		if (BrandList == null){
			//carProcess.downloadData(strReString,null);
		}
		else if((BrandList != null) && (BrandList.size() > 0)){
			BrandAdapter localBrandAdapter = new BrandAdapter(mContext);
		    localBrandAdapter.setList(BrandList);
			
		    localBrandAdapter.setListView(this.listView);
		    listView.setAdapter(localBrandAdapter);
		    listView.setOnItemClickListener(itemClickListener);//监听事件
		    listView.setOnScrollListener(scrollListener);//给ListView注册滚动监听
		}
	}
	
	
	/**
	 * listview 监听事件
	 * @param method
	 * @param param
	 */
	private OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view, int index,
				long time) {
		    int position = index;
		    int id = ((Brand)BrandList.get(index)).getId();
		    String name = ((Brand)BrandList.get(index)).getName();
			BrandListActivity.launch(mContext,position,id,name);
		}
	};
	
	/**
	 * listview滚动监听事件
	 */
    public OnScrollListener scrollListener = new OnScrollListener() {
    	
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			int lastItem = firstVisibleItem + visibleItemCount - 1;
	        if (mReady) {
	        	char firstLetter = mStrings[firstVisibleItem+3].charAt(0);
	            
	            if (!mShowing && firstLetter != mPrevLetter) {
	                mShowing = true;
	                mDialogText.setVisibility(View.VISIBLE);
	            }
	            mDialogText.setText(((Character)firstLetter).toString());
	            mHandler.removeCallbacks(mRemoveWindow);
	            mHandler.postDelayed(mRemoveWindow, 3000);
	            mPrevLetter = firstLetter;
	        }
		}
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) { 

		}
	};
	
}
